package com.acs.player.views.cover;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Shader.TileMode;
import android.net.Uri;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

import com.acs.player.CoverActivity;
import com.acs.player.CoverFlowActivity;
import com.acs.player.R;
import com.acs.player.entities.Album;

public class ImageAdapter extends BaseAdapter {
	
	private Activity currentActivity;
    private List<Album> albumsList;

    public ImageAdapter(Activity currentActivity, List<Album> albumsList) {
    	this.currentActivity = currentActivity;
        this.albumsList = albumsList;
    }

    @Override
    public int getCount() {
        return albumsList.size();
    }

    @Override
    public Object getItem(int position) {
        return albumsList.get(position);
    }
    
	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return 0;
	}

    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView = null;
        if (convertView == null) {  // if it's not recycled, initialize some attributes
            imageView = new ImageView(currentActivity);
            if(currentActivity instanceof CoverActivity){
                imageView.setLayoutParams(new GridView.LayoutParams(110, 110));
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            } else if(currentActivity instanceof CoverFlowActivity){
        		imageView.setLayoutParams(new Gallery.LayoutParams(150, 220));
        		imageView.setScaleType(ScaleType.FIT_XY);
            }
            
            Album album = albumsList.get(position);       
            String coverPath = album.getImagePath();
            String albumName = album.getNom();
                 
            if(currentActivity instanceof CoverActivity){	    
                if(coverPath != null){
    				Uri artworkUri = Uri.parse(coverPath);
    				imageView.setImageURI(artworkUri);
                } else {
    	        	imageView.setImageResource(R.drawable.no_cover);
    	        }
    			
            } else if(currentActivity instanceof CoverFlowActivity){
    	
            	CoverFlowActivity coverFlowActivity = (CoverFlowActivity) currentActivity;
            	
        		Bitmap bm = null;  
        		if(coverPath != null){
    		            	
    				try {
    					File file = new File(coverPath);
    					FileInputStream fis = new FileInputStream(file);
    					FileDescriptor fileDescriptor = fis.getFD();
    					bm = BitmapFactory.decodeFileDescriptor(fileDescriptor);
    				} catch (FileNotFoundException e) {
    					e.printStackTrace();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}    
    				
    	            if(bm == null){
    	            	bm = BitmapFactory.decodeResource(currentActivity.getResources(), R.drawable.no_cover);
    	            }
    	            
        		} else {
        			bm = BitmapFactory.decodeResource(currentActivity.getResources(), R.drawable.no_cover);
        		}
        		
        		Bitmap output = createReflectedImage(currentActivity, bm);
        		imageView.setImageBitmap(output);  
        		
 
           		TextView textView = (TextView) coverFlowActivity.findViewById(R.id.textViewCoverFlow);
        		if(albumName != null){
        			textView.setText(albumName);
        		} else {
        			textView.setText(R.string.unknown);
        		}
        		
    	    }
    		
    		imageView.setTag(position);
    		
            imageView.setOnClickListener(new OnClickListener() {		
    			@Override
    			public void onClick(View view) {
    				int indexAlbum = (Integer) view.getTag();
    				if(currentActivity instanceof CoverActivity){
    					CoverActivity coverActivity = (CoverActivity) currentActivity;	
    					coverActivity.goToCoverViewRow(indexAlbum);
    				} else if(currentActivity instanceof CoverFlowActivity){
    					CoverFlowActivity coverFlowActivity = (CoverFlowActivity) currentActivity;
    					coverFlowActivity.goToCoverViewRow(indexAlbum);
    				}
    			}
    		});
        } else {
            imageView = (ImageView) convertView;
        }  
        
        
        return imageView;
    }
    
	private Bitmap createReflectedImage(Context context, Bitmap originalImage) {
		//The gap we want between the reflection and the original image
		final int reflectionGap = 4;
		int width = originalImage.getWidth();
		int height = originalImage.getHeight();

		//This will not scale but will flip on the Y axis
		Matrix matrix = new Matrix();
		matrix.preScale(1, -1);
		  
		//Create a Bitmap with the flip matrix applied to it.
		//We only want the bottom half of the image
		Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, height/2, width, height/2, matrix, false);

		//Create a new bitmap with same width but taller to fit reflection
		Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + height/2), Config.ARGB_8888);
		  
		//Create a new Canvas with the bitmap that's big enough for
		//the image plus gap plus reflection
		Canvas canvas = new Canvas(bitmapWithReflection);
		//Draw in the original image
		canvas.drawBitmap(originalImage, 0, 0, null);
		//Draw in the gap
		Paint defaultPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
		canvas.drawRect(0, height, width, height + reflectionGap, defaultPaint);
		//Draw in the reflection
		canvas.drawBitmap(reflectionImage,0, height + reflectionGap, null);
		 
		//Create a shader that is a linear gradient that covers the reflection
		Paint paint = new Paint();
		LinearGradient shader = new LinearGradient(0, originalImage.getHeight(), 0,
		bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff,
		TileMode.CLAMP);
		//Set the paint to use this shader (linear gradient)
		paint.setShader(shader);
		//Set the Transfer mode to be porter duff and destination in
		paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
		//Draw a rectangle using the paint with our linear gradient
		canvas.drawRect(0, height, width,
		bitmapWithReflection.getHeight() + reflectionGap, paint);
		
		return bitmapWithReflection;
	}
}